//
//  STRefreshViewController.swift
//  iPhone
//
//  Created by Toj on 1/30/23.
//

import UIKit
import MJRefresh

class STRefreshViewController: STBaseViewController {
    
    private lazy var data: [UIColor] = [] { didSet {
        collectionView.reloadData()
    } }
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: 104, height: 124)
        
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.scrollsToTop = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.backgroundColor = .white
        view.register(cellClass: RefreshCell.self)
        view.mj_header = headerView
        view.mj_footer = footerView
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    private lazy var headerView: MJRefreshStateHeader = {
        let view = MJRefreshStateHeader()
        view.mj_h = 0.5
        view.stateLabel?.isHidden = true
        view.lastUpdatedTimeLabel?.isHidden = true
        view.setRefreshingTarget(self, refreshingAction: #selector(loadFirstData))
        return view
    }()
    
    private lazy var footerView: MJRefreshAutoNormalFooter = {
        let view = MJRefreshAutoNormalFooter()
        view.setTitle("", for: .idle)
        view.setTitle("松开就可以进行刷新的状态", for: .pulling)
        view.setTitle("即将刷新的状态", for: .willRefresh)
        view.setTitle("正在刷新中的状态", for: .refreshing)
        view.setTitle("noMoreData", for: .noMoreData)
        view.setRefreshingTarget(self, refreshingAction: #selector(loadMoreData))
        
        return view
    }()
    
    private lazy var refreshButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = .white
        view.setTitle("Refresh", for: .normal)
        view.setTitleColor(.red, for: .normal)
        view.addTarget(self, action: #selector(didTapRefresh), for: .touchUpInside)
        return view
    }()
    
    private var pageNumber = 0
    private let pageEnd = 3
    
    private func endRefreshing(_ isFirst: Bool = false) {
        print("-->toj: pageNumber: \(pageNumber)")
        let refreshView = isFirst ? collectionView.mj_header : collectionView.mj_footer
        if pageNumber >= pageEnd || data.count > 20 {
            refreshView?.endRefreshing()
            collectionView.mj_footer?.endRefreshingWithNoMoreData()
            return
        }
        
        let contentSizeHeight = collectionView.contentSize.height
        guard contentSizeHeight < collectionView.frame.height else {
            refreshView?.endRefreshing()
            return
        }
        
        // 不延迟0.2秒 mj_footer不显示
        DispatchQueue.main.asyncAfter(deadline: .now()+0.01) { [weak self] in
            self?.footerView.beginRefreshing()
        }
    }
    
    @objc func loadFirstData() {
        pageNumber = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            var ds = [UIColor]()
            let pageCount = 2 // Int(arc4random_uniform(10)) + 5
            for _ in 0..<pageCount {
                ds.append(.random)
            }

            self.collectionView.mj_header?.isHidden = true
            self.data = ds
            self.collectionView.mj_header?.endRefreshing { [weak self] in
                print("-->toj: mj_header endRefreshing callback")
                self?.endRefreshing(true)
            }
        }
    }
    
    @objc func loadMoreData() {
        pageNumber += 1
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            var ds = [UIColor]()
            let pageCount = 1 // Int(arc4random_uniform(1))
            for _ in 0..<pageCount {
                ds.append(.random)
            }
            
            self.data.append(contentsOf: ds)
            self.collectionView.mj_footer?.endRefreshing { [weak self] in
                print("-->toj: mj_footer endRefreshing callback")
                self?.endRefreshing()
            }
        }
    }
    
    @objc func didTapRefresh() {
        navigationController?.popToRootViewController(animated: true)
        
        footerView.endRefreshingWithNoMoreData()
        
        //collectionView.reloadData()
        //collectionView.mj_header?.beginRefreshing()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .gray
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.top.equalTo(CGFloat.nav_barFullHeight)
        }
        
        view.addSubview(refreshButton)
        refreshButton.snp.makeConstraints { make in
            make.centerX.equalTo(view)
            make.top.equalTo(CGFloat.nav_barFullHeight)
            make.width.equalTo(100)
            make.height.equalTo(44)
        }
        collectionView.mj_header?.beginRefreshing()
    }
}

extension STRefreshViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifierClass: RefreshCell.self, for: indexPath)
        cell.numberString = indexPath.row.to_string
        cell.contentView.backgroundColor = data[indexPath.row]
        return cell
    }
}

extension STRefreshViewController: UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let _ = cell as? RefreshCell else { return }
        // print("-->toj: willDisplay number: \(recell.numberString)")
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let _ = cell as? RefreshCell else { return }
        // print("-->toj: didEndDisplaying number: \(recell.numberString)")
    }
}
